<?php
namespace Custom\ExamBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Topxia\Common\ArrayToolkit;
use Topxia\Common\Paginator;
use Topxia\WebBundle\Controller\CourseTestpaperManageController;
use Custom\Common\ExamEnum;

class CourseTestpaperManageExtController extends CourseTestpaperManageController
{
	public function indexAction(Request $request)
	{
        $courseId = 1;
		$course = $this->getCourseService()->tryManageCourse($courseId);

		$conditions = array();
		$conditions['target'] = "course-{$course['id']}";
		$paginator = new Paginator(
				$this->get('request'),
				$this->getTestpaperService()->searchTestpapersCount($conditions),
				10
		);

		$testpapers = $this->getTestpaperService()->searchTestpapers(
				$conditions,
				array('createdTime' ,'DESC'),
				$paginator->getOffsetCount(),
				$paginator->getPerPageCount()
		);

		$users = $this->getUserService()->findUsersByIds(ArrayToolkit::column($testpapers, 'updatedUserId'));
	
		return $this->render('CustomExamBundle:CourseTestpaperManage:index.html.twig', array(
				'course' => $course,
				'testpapers' => $testpapers,
				'users' => $users,
				'paginator' => $paginator,
		));
	}
	
	public function createAction(Request $request, $courseId)
	{
		$course = $this->getCourseService()->tryManageCourse($courseId);
	
		if ($request->getMethod() == 'POST') {
			$fields = $request->request->all();
			$fields['ranges'] = empty($fields['ranges']) ? array() : explode(',', $fields['ranges']);
			$fields['target'] = "course-{$course['id']}";
			$fields['pattern'] = 'QuestionType';
			list($testpaper, $items) = $this->getTestpaperExtService()->createTestpaper($fields);
			return $this->redirect($this->generateUrl('course_manage_testpaper_design',array('courseId' => $course['id'], 'testpaperId' => $testpaper['id'])));
		}

		return $this->render('CustomExamBundle:CourseTestpaperManage:create.html.twig', array(
				'course'    => $course,
				'ranges' => $this->getQuestionRanges($course),
				//'types' => $types,
		));
	}

    public function itemsAction(Request $request, $courseId, $testpaperId)
    {
        $course = $this->getCourseService()->tryManageCourse($courseId);

        $testpaper = $this->getTestpaperService()->getTestpaper($testpaperId);
        if(empty($testpaper)){
            throw $this->createNotFoundException('试卷不存在');
        }

        if ($request->getMethod() == 'POST') {
            $data = $request->request->all();

            if (empty($data['questionId']) or empty($data['scores'])) {
                return $this->createMessageResponse('error', '试卷题目不能为空！');
            }
            if (count($data['questionId']) != count($data['scores'])) {
                return $this->createMessageResponse('error', '试卷题目数据不正确');
            }

            $data['questionId'] = array_values($data['questionId']);
            $data['scores'] = array_values($data['scores']);

            $items = array();
            foreach ($data['questionId'] as $index => $questionId) {
                $items[] = array('questionId' => $questionId, 'score' => $data['scores'][$index]);
            }

            $this->getTestpaperService()->updateTestpaperItems($testpaper['id'], $items);

            $this->setFlashMessage('success', '试卷题目保存成功！');
            return $this->redirect($this->generateUrl('course_manage_testpaper',array( 'courseId' => $courseId)));
        }

        $items = $this->getTestpaperService()->getTestpaperItems($testpaper['id']);

        $questions = $this->getQuestionService()->findQuestionsByIds(ArrayToolkit::column($items, 'questionId'));

        $subItems = array();
        foreach ($items as $key => $item) {
            if ($item['parentId'] > 0) {
                $subItems[$item['parentId']][] = $item;
                unset($items[$key]);
            }
        }

        return $this->render('CustomExamBundle:CourseTestpaperManage:items.html.twig', array(
            'course' => $course,
            'testpaper' => $testpaper,
            'items' => ArrayToolkit::question($items, 'questionType'),
            'subItems' => $subItems,
            'questions' => $questions,
            'targets' => $this->getCategoryes(),
        ));
    }

	public function itemPickerAction(Request $request, $courseId, $testpaperId)
	{
        $course = $this->getCourseService()->tryManageCourse($courseId);
        $testpaper = $this->getTestpaperService()->getTestpaper($testpaperId);
        if (empty($testpaper)) {
            throw $this->createNotFoundException();
        }

        $conditions = $request->query->all();

        if (empty($conditions['target'])) {
            $conditions['targetPrefix'] = "course-{$course['id']}";
        }

        $conditions['parentId'] = 0;
        $conditions['excludeIds'] = empty($conditions['excludeIds']) ? array() : explode(',', $conditions['excludeIds']);

        if (!empty($conditions['keyword'])) {
            $conditions['stem'] = $conditions['keyword'];
        }


        $replace = empty($conditions['replace']) ? '' : $conditions['replace'];

        $paginator = new Paginator(
            $request,
            $this->getQuestionService()->searchQuestionsCount($conditions),
            7
        );

        $questions = $this->getQuestionService()->searchQuestions(
                $conditions, 
                array('createdTime' ,'DESC'), 
                $paginator->getOffsetCount(),
                $paginator->getPerPageCount()
        );

        //$targets = $this->get('topxia.target_helper')->getTargets(ArrayToolkit::column($questions, 'target'));

        return $this->render('TopxiaWebBundle:CourseTestpaperManage:item-picker-modal.html.twig', array(
            'course' => $course,
            'testpaper' => $testpaper,
            'questions' => $questions,
            'replace' => $replace,
            'paginator' => $paginator,
            'targetChoices' => $this->getCategoryes(),
            'targets' =>  $this-> getTargets(),
            'conditions' => $conditions,
        ));
	}
	
	public function buildCheckAction(Request $request, $courseId)
	{
		$course = $this->getCourseService()->tryManageCourse($courseId);
	
		$data = $request->request->all();
		$data['target'] = "course-{$course['id']}";
		$data['ranges'] = empty($data['ranges']) ? array() : explode(',', $data['ranges']);
		$result = array("status"=>"yes","missing"=>"");
		return $this->createJsonResponse($result);
	}
	
	public function designAction(Request $request, $courseId, $testpaperId) {
// echo '此处试题列表';die;
		// $course = $this->getCourseService()->tryManageCourse($courseId);
		// $testpaper = $this->getTestpaperService()->getTestpaper($testpaperId);

		// if(empty($testpaper)){
		// 	throw $this->createNotFoundException('试卷不存在');
		// }
		
		// $conditions = $request->query->all();
		// $paginator = new Paginator(
		// 		$this->get('request'),
		// 		$this->getQuestionService()->searchQuestionsCount($conditions),
		// 		10
		// );

        $grades = ExamEnum::getGrades();
        $subjects = ExamEnum::getSubjects();
		//题型questionType
		$questionTypes = $this->get('topxia.twig.web_extension')->getDict('questionType');
		//难度difficulty
		$difficultys = $this->get('topxia.twig.web_extension')->getDict('difficulty');
		// return $this->render('CustomExamBundle:CourseTestpaperManage:design.html.twig', array(
		// 		'questionTyles' =>$questionTypes,
		// 		'difficultys'=>$difficultys,
		// 		'course' => $course,
		// 		'testpaper' => $testpaper,
		// 		'paginator' => $paginator,
		// 		'conditions' => $conditions,
		// 		'targetCategoryes' => $this->getCategoryes(),
  //               'grades'=>$grades,
  //               'subjects'=>$subjects,
		// ));
        $question = $this->getQuestionService()->getAll();
        $page = empty($_GET['page']) ? 1 : $_GET['page'];
        $limit = 20;
        $count =  $this->getQuestionService()->getQuestionTotal();
        $maxPage = $count['total'] ? ceil($count['total'] / $limit) : 1;
        $page = $page <= 0 ? 1 : $page > $maxPage ? $maxPage : $page;
        $offset = ($page - 1)*$limit;
        $question = array_slice($question,$offset,$limit);
        $paginator = new Paginator($this->get('request'), $count['total'], $limit);
        return $this->render('CustomExamBundle:CourseTestpaperManage:design.html.twig',array(
            'question'=>$question, 
            'paginator' => $paginator,
            'difficultys'=>$difficultys,
           	'grades'=>$grades,
            'subjects'=>$subjects,
            'questionTyles' =>$questionTypes,
        ));
	}

	public function designQuestionListAction(Request $request, $testpaperId){
		$testpaper = $this->getTestpaperService()->getTestpaper($testpaperId);
		if(empty($testpaper)){
			throw $this->createNotFoundException('试卷不存在');
		}
		$items = $this->getTestpaperService()->getTestpaperItems($testpaper['id']);
		$paperQuestionIds = ArrayToolkit::column($items, 'questionId');

		$conditions = $request->query->all();
	
		$conditions["parentId"] = "0";
		if (isset($conditions['type']) && $conditions['type'] == "0") {
			unset($conditions['type']);
		}
		if (isset($conditions['difficulty']) && $conditions['difficulty'] == "0") {
			unset($conditions['difficulty']);
		}
        if (isset($conditions['grade']) && $conditions['grade'] == "0") {
            unset($conditions['grade']);
        }
        if (isset($conditions['subject']) && $conditions['subject'] == "0") {
            unset($conditions['subject']);
        }
 		if (isset($conditions['nselect']) && $conditions['nselect'] != "0") {
			$conditions["targetPrefix"] = "category-". $conditions['nselect'];
			unset($conditions['nselect']);
		} 
		
		
		$paginator = new Paginator(
				$this->get('request'),
				$this->getQuestionExtService()->searchQuestionsCount($conditions),
				10
		);
	
		$orderBy = array('createdTime' ,'DESC');
		$questions = $this->getQuestionExtService()->searchQuestions(
				$conditions,
				$orderBy,
				$paginator->getOffsetCount(),
				$paginator->getPerPageCount()
		);
		
		$questionList = array();
		foreach ($questions as $question){
			if (in_array( $question["id"], $paperQuestionIds )) {
				$question["isSelected"] = true;
			}
			else {
				$question["isSelected"] = false;
			}
			
			if($question["parentId"] == 0){
				$questionList[] = $question;
			}
		}
		
		return $this->render('CustomExamBundle:CourseTestpaperManage:design-question-list.html.twig', array(
				'questions' => $questionList,
				'paginator' => $paginator,
				'conditions' => $conditions
		));
	}
	
	private function getQuestionRanges($course, $includeCourse = false)
	{
		$lessons = $this->getCourseService()->getCourseLessons($course['id']);
		$ranges = array();
	
		if ($includeCourse == true) {
			$ranges["course-{$course['id']}"] = '本课程';
		}
	
		foreach ($lessons as  $lesson) {
			if ($lesson['type'] == 'testpaper') {
				continue;
			}
			$ranges["course-{$lesson['courseId']}/lesson-{$lesson['id']}"] = "课时{$lesson['number']}： {$lesson['title']}";
		}
	
		return $ranges;
	}
	
	private function getTargets()
	{
		$categories = $this->getCategoryService()->getCategoryTree(1);
		$choices = array();
		foreach ($categories as $category) {
			$categoryName = array("simple_name"=>$category['name']);
			$choices["category-".$category['id']] = $categoryName;
		}
		return $choices;
	}
	
	private function getCategoryes()
	{
		$categories = $this->getCategoryService()->getCategoryTree(1);
		$choices = array();
		foreach ($categories as $category) {
            $categoryName = $category['name'];
            for ($i = 2; $i <= $category["depth"]; $i++)
            {
                $categoryName = "&nbsp;&nbsp;&nbsp;". $categoryName;
            }
			$choices["category-".$category['id']] = $categoryName;
		}
		return $choices;
	}
		
	private function getCategoryService()
	{
		return $this->getServiceKernel()->createService('Taxonomy.CategoryService');
	}
	
	private function getCourseService()
	{
		return $this->getServiceKernel()->createService('Course.CourseService');
	}
	
	private function getTestpaperService()
	{
		return $this->getServiceKernel()->createService('Testpaper.TestpaperService');
	}
	
	private function getTestpaperExtService()
	{
		return $this->getServiceKernel()->createService('Testpaper.TestpaperService');
	}
	
	private function getQuestionService()
	{
		return $this->getServiceKernel()->createService('Question.QuestionService');
	}
	
 	private function getQuestionExtService()
	{
		return $this->getServiceKernel()->createService('Custom:Question.QuestionService');
	}

    // private function getQuestionService(){
    //     return $this->getServiceKernel()->createService('Question.QuestionService');
    // }

}